package com.taobaostore.service.impl;

import static org.hamcrest.CoreMatchers.nullValue;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.api.AlipayResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.demo.trade.config.Configs;
import com.alipay.demo.trade.model.ExtendParams;
import com.alipay.demo.trade.model.GoodsDetail;
import com.alipay.demo.trade.model.builder.AlipayTradePrecreateRequestBuilder;
import com.alipay.demo.trade.model.result.AlipayF2FPrecreateResult;
import com.alipay.demo.trade.service.AlipayTradeService;
import com.alipay.demo.trade.service.impl.AlipayTradeServiceImpl;
import com.alipay.demo.trade.utils.ZxingUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.taobaostore.common.AliyunOSSUtil;
import com.taobaostore.common.BigDecimalUtil;
import com.taobaostore.common.Const;
import com.taobaostore.common.ServerResponse;
import com.taobaostore.dao.CartMapper;
import com.taobaostore.dao.OrderItemMapper;
import com.taobaostore.dao.OrderMapper;
import com.taobaostore.dao.PayInfoMapper;
import com.taobaostore.dao.ProductMapper;
import com.taobaostore.dao.ReceiverMapper;
import com.taobaostore.pojo.Cart;
import com.taobaostore.pojo.Order;
import com.taobaostore.pojo.OrderItem;
import com.taobaostore.pojo.PayInfo;
import com.taobaostore.pojo.Product;
import com.taobaostore.pojo.Receiver;
import com.taobaostore.pojo.User;
import com.taobaostore.service.IOrderService;
import com.taobaostore.util.DateTimeUtil;
import com.taobaostore.util.FTPUtil;
import com.taobaostore.util.PropertiesUtil;
import com.taobaostore.vo.CartProductVo;
import com.taobaostore.vo.CartVo;
import com.taobaostore.vo.OrderItemVo;
import com.taobaostore.vo.OrderProductVo;
import com.taobaostore.vo.OrderVo;
import com.taobaostore.vo.ReceiverVo;
@Service("iOrderService")
public class OrderServiceImpl implements IOrderService{

	private static Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);
	@Autowired
	private OrderMapper orderMapper;

	@Autowired
	private OrderItemMapper orderItemMapper;

	@Autowired
	private ProductMapper productMapper;

	@Autowired
	private PayInfoMapper payInfoMapper;

	@Autowired
	private CartMapper cartMapper;

	@Autowired
	private ReceiverMapper receiverMapper;

    /**
     * 更新订单状态
     */
	public ServerResponse<String> updateOrderStatus(Integer userId,Long orderOn,Integer statusCode) {
		Order order = orderMapper.selectByOrderNo(orderOn);
		if (null == order) {
			return ServerResponse.createByError("找不到订单信息!");
		}
		order.setStatus(statusCode);
		int rowCount = orderMapper.updateByPrimaryKeySelective(order);
		if (rowCount == 1) {
			return ServerResponse.createBySuccess("订单状态切换成功!");
		}
		return null;
	}
	
	

	/**
	 * 后台查询订单列表
	 * @param userId
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	public ServerResponse<PageInfo<OrderVo>> manageList(Integer pageNum,Integer pageSize) {
		List<OrderVo> list = Lists.newArrayList();
		// 先获取用户下的所有订单信息
		PageHelper.startPage(pageNum, pageSize);
		List<Order> orders = orderMapper.listOrder();
		// 为每个订单填充数据
		for (Order order : orders) {
			// 获取每个订单下的订单子项
			List<OrderItemVo> orderItemVos = Lists.newArrayList();
			List<OrderItem> orderItems = orderItemMapper.listOrderItemByOrderOn(order.getOrderNo());
			for (OrderItem orderItem : orderItems) {
				orderItemVos.add(transformOrderItemVo(orderItem));
			}
			list.add(transformOrderVo(order, orderItems));
		}
		if (CollectionUtils.isEmpty(list)) {
			return ServerResponse.createByError("没有找到数据!");
		}
		PageInfo<OrderVo> pageInfo = new PageInfo<OrderVo>(list);
		int pageCount = orderMapper.countOrder();
		pageInfo.setPages(pageCount % pageSize==0?pageCount/pageSize:pageCount/pageSize+1);
		return ServerResponse.createBySuccess(pageInfo);
	}





	/**
	 *   取消订单
	 * @param userId
	 * @param orderOn
	 * @return
	 */
	public ServerResponse<String> cancelOrder(Integer userId,Long orderOn){
		Order order = orderMapper.selectByUserIdAndOrderNo(userId, orderOn);
		if (null == order) {
			return ServerResponse.createByError("删除订单失败,找不到订单!");
		}
		int rowCount = orderMapper.updateOrderStatus(userId, orderOn);
		if (rowCount == 1) {
			return ServerResponse.createBySuccess("取消订单成功!");
		}
		return ServerResponse.createByError("发生未知错误,请联系管理员!");
	}




	/**
	 * 查询当前用户下的所有订单信息
	 * @param userId
	 * @return
	 */
	public ServerResponse<List<OrderVo>> getOrderVo(Integer userId){
		List<OrderVo> list = Lists.newArrayList();
		// 先获取用户下的所有订单信息
		List<Order> orders = orderMapper.listOrderByUserId(userId);
		// 为每个订单填充数据
		for (Order order : orders) {
			// 获取每个订单下的订单子项
			List<OrderItemVo> orderItemVos = Lists.newArrayList();
			List<OrderItem> orderItems = orderItemMapper.listOrderItemByIdAndUserId(userId, order.getOrderNo());
			for (OrderItem orderItem : orderItems) {
				orderItemVos.add(transformOrderItemVo(orderItem));
			}
			list.add(transformOrderVo(order, orderItems));
		}
		return ServerResponse.createByError(list);
	}






	public ServerResponse<CartVo> listCartProductVo(Integer userId){
		CartVo cartVo = new CartVo();
		List<CartProductVo> cartProductVoList = Lists.newArrayList();
		List<Cart> cartList = cartMapper.listCartByUserIdAndChecked(userId);

		BigDecimal bigDecimal = new BigDecimal("0");
		for (Cart cart : cartList) {
			CartProductVo cartProductVo = new CartProductVo();
			cartProductVo.setId(cart.getId());
			cartProductVo.setUserId(userId);
			cartProductVo.setProductId(cart.getProductId());

			Product product = productMapper.getProductById(cartProductVo.getProductId());
			cartProductVo.setProductMainImage(product.getMainImage());
			cartProductVo.setProductName(product.getName());
			cartProductVo.setProductPrice(product.getPrice());
			cartProductVo.setProductStatus(product.getStatus());
			cartProductVo.setProductStock(product.getStock());
			cartProductVo.setProductTotalPrice(BigDecimalUtil.mul(cart.getQuantity(),product.getPrice().doubleValue()));
			cartProductVo.setProductChecked(cart.getChecked());
			cartProductVo.setProductSubtitle(product.getSubtitle());
			cartProductVo.setQuantity(cart.getQuantity());
			cartProductVo.setLimitQuantity(Const.Cart.LIMIT_NUM_SUCCESS);
			// 新增商品总价格
			bigDecimal = BigDecimalUtil.add(bigDecimal.doubleValue(),cartProductVo.getProductTotalPrice().doubleValue());
			cartProductVoList.add(cartProductVo);
		}
		cartVo.setCartTotalPrice(bigDecimal);
		cartVo.setCartProductVoList(cartProductVoList);
		return ServerResponse.createBySuccess(cartVo);
	}








	/**
	 * 新增订单记录
	 * @param userId
	 * @param receiverId
	 * @return
	 */
	public ServerResponse<Object> create(Integer userId,Integer receiverId){
		// 查询当前用户下被选中的购物车记录
		List<Cart> cartList = cartMapper.listCartByUserIdAndChecked(userId);
		// 获取订单子表记录
		ServerResponse<List<OrderItem>> orderItems = this.getOrderItem(userId, cartList);
		if (!orderItems.isSuccess()) {
			return ServerResponse.createByError("发生错误!");
		}
		// 此时订单记录新增完毕
		Order order = this.createOrder(userId, receiverId, this.calculate(orderItems.getData()));
		for (OrderItem orderItem : orderItems.getData()) {
			orderItem.setOrderNo(order.getOrderNo());
		}
		System.out.println("======================订单子项===================");
		System.out.println(orderItems.getData());
		System.out.println("======================订单子项===================");
		// 批量插入订单子项
		this.batchOrderItem(orderItems.getData());
		// 生成成功,我们要减少我们产品的库存
		this.reduceProductStock(orderItems.getData());
		// 清除购物车
		this.cleanCart(cartList);
		//将订单对象封装成Vo模型返回给前端
		OrderVo orderVo = this.transformOrderVo(order, orderItems.getData());
		return ServerResponse.createBySuccess(orderVo);
	}



	/**
	 * 更新商品的库存
	 * @param orderItems
	 */
	public void reduceProductStock(List<OrderItem> orderItems) {
		for (OrderItem orderItem : orderItems) {
			Product product = productMapper.getProductById(orderItem.getProductId());
			// 将商品改为未选中
			product.setStock(product.getStock() - orderItem.getQuantity());
			productMapper.updateByPrimaryKeySelective(product);
		}
	}



	/**
	 * 批量插入OrderItem
	 * @param orderItems
	 * @return
	 */
	public ServerResponse batchOrderItem(List<OrderItem> orderItems) {
		int rowCount = orderItemMapper.batchOrderItem(orderItems);
		if (rowCount > 0) {
			return ServerResponse.createBySuccess();
		}
		return ServerResponse.createByError();
	}


	/**
	 * 新增订单记录
	 * @param userId 用户id
	 * @param receiver_id 收货地址id
	 * @param payment 订单总价格
	 * @return
	 */
	public Order createOrder(Integer userId,Integer receiver_id,BigDecimal payment) {
		Order order = new Order();
		long orderOn = this.getOrderOn();
		order.setOrderNo(orderOn);
		order.setPayment(payment);
		order.setPostage(0);
		order.setStatus(Const.OrderStatusEnum.NO_PAY.getCode());
		order.setPaymentType(Const.PayPlatformEnum.ALIPAY.getCode());
		order.setUserId(userId);
		order.setReceiverId(receiver_id);
		int rowCount = orderMapper.insert(order);
		if (rowCount == 1) {
			return order;
		}
		return null;
	}



	/**
	 * 计算订单总价格
	 * @param orderItems
	 * @return
	 */
	public BigDecimal calculate(List<OrderItem> orderItems) {
		BigDecimal payment = new BigDecimal("0");
		for (OrderItem orderItem : orderItems) {
			payment = BigDecimalUtil.add(payment.doubleValue(), orderItem.getTotalPrice().doubleValue());
		}
		return payment;
	}



	/**
	 * 封装入OrderItem集合后,清除购物车
	 * @param carts
	 * @return
	 */
	public ServerResponse cleanCart(List<Cart> carts){
		if (CollectionUtils.isEmpty(carts)) {
			return ServerResponse.createByError();
		}
		for (Cart cart : carts) {
			cartMapper.deleteByCartId(cart.getId());
		}
		return ServerResponse.createBySuccess();
	}



	/**
	 * 根据用户和购物车封装好订单子项对象集合
	 * @param userId
	 * @param carts
	 * @return
	 */
	public ServerResponse<List<OrderItem>> getOrderItem(Integer userId,List<Cart> carts){
		List<OrderItem> orderItems = Lists.newArrayList();
		if (CollectionUtils.isEmpty(carts)) {
			return ServerResponse.createByError("购物车为空");
		}
		// 遍历购物车来填充订单子表记录
		for (Cart cart : carts) {
			OrderItem orderItem = new OrderItem();
			Product product = productMapper.getProductById(cart.getProductId());// 查询出指定购物车下的商品信息
			// 判断商品状态
			if (Const.ProductStatus.SALL.getCode() != product.getStatus()) {
				return ServerResponse.createByError("商品非在售状态!");
			}
			// 判断数量够不够
			if (product.getStock() < cart.getQuantity()) {
				return ServerResponse.createByError("商品数量不足您购买!!请重新下单!!");
			}
			orderItem.setUserId(userId);
			orderItem.setProductId(product.getId());
			orderItem.setProductName(product.getName());
			orderItem.setProductImage(product.getMainImage());
			orderItem.setCurrentUnitPrice(product.getPrice());
			orderItem.setQuantity(cart.getQuantity());
			orderItem.setTotalPrice(BigDecimalUtil.mul(orderItem.getQuantity().doubleValue(),orderItem.getCurrentUnitPrice().doubleValue()));
			orderItems.add(orderItem);
		}
		return ServerResponse.createBySuccess(orderItems);
	}




	/**
	 * 生成订单号策略
	 * @return
	 */
	public long getOrderOn() {
		long currentTime = System.currentTimeMillis();
		return currentTime + currentTime % 10;
	}


	/**
	 * Order转换为VO模型对象
	 * @param orderItem
	 * @return
	 */
	public OrderItemVo transformOrderItemVo(OrderItem orderItem) {
		OrderItemVo orderItemVo = new OrderItemVo();
		orderItemVo.setOrderNo(orderItem.getOrderNo());
		orderItemVo.setProductId(orderItem.getProductId());
		orderItemVo.setProductName(orderItem.getProductName());
		orderItemVo.setProductImage(orderItem.getProductImage());
		orderItemVo.setQuantity(orderItem.getQuantity());
		orderItemVo.setCurrentUnitPrice(orderItem.getCurrentUnitPrice());
		orderItemVo.setTotalPrice(orderItem.getTotalPrice());
		orderItemVo.setCreateTime(DateTimeUtil.DateTostr(orderItem.getCreateTime()));
		return orderItemVo;
	}

	/**
	 * 获取模型OrderProductVo对象
	 * @param userId
	 * @return
	 */
	public OrderProductVo transformOrderProductVo(Integer userId) {
		List<Cart> carts = cartMapper.listCartByUserIdAndChecked(userId);// 查询出当前购物车下
		ServerResponse serverResponse = this.getOrderItem(userId, carts);
		List<OrderItem> orderItemList = (List<OrderItem>) serverResponse.getData();
		// 初始化需要的值
		OrderProductVo orderProductVo = new OrderProductVo();
		BigDecimal payment = new BigDecimal("0");
		List<OrderItemVo> orderItemVoList = Lists.newArrayList();

		for (OrderItem orderItem : orderItemList) {
			payment = BigDecimalUtil.add(payment.doubleValue(),orderItem.getTotalPrice().doubleValue());
			orderItemVoList.add(transformOrderItemVo(orderItem));
		}


		orderProductVo.setOrderItemVoList(orderItemVoList);
		orderProductVo.setProductTotalPrice(payment);
		orderProductVo.setImageHost(PropertiesUtil.getValue("FTP_IP"));
		return orderProductVo;
	}

	/**
	 * 转换获得订单Vo
	 * @param order
	 * @param listOrderItem
	 * @return
	 */
	public OrderVo transformOrderVo(Order order,List<OrderItem> listOrderItem) {
		OrderVo orderVo = new OrderVo();
		orderVo.setOrderNo(order.getOrderNo());
		orderVo.setPayment(order.getPayment());
		orderVo.setPaymentType(order.getPaymentType());
		orderVo.setPaymentTime(order.getPaymentTime());
		orderVo.setPaymentTypeDesc(Const.PaymentType.ON_LINE.getValue());

		orderVo.setPostage(order.getPostage());
		orderVo.setStatus(order.getStatus());

		//获取收货地址信息
		Receiver receiver = receiverMapper.getReceiverById(order.getReceiverId());
		if (null != receiver) {
			orderVo.setReceiverId(receiver.getId());
			orderVo.setReceiverVo(this.transformReceiverVo(receiver));
		}
		// 填充订单子项Vo
		List<OrderItemVo> listOrderItemVo = Lists.newArrayList();
		for (OrderItem orderItem : listOrderItem) {
			OrderItemVo vo = this.transformOrderItemVo(orderItem);
			listOrderItemVo.add(vo);
		}
		orderVo.setListOrderItemVo(listOrderItemVo);
		return orderVo;
	}

	public ReceiverVo transformReceiverVo(Receiver receiver) {
		ReceiverVo receiverVo = new ReceiverVo();
		receiverVo.setReceiverName(receiver.getReceiverName());
		receiverVo.setReceiverAddress(receiver.getReceiverAddress());
		receiverVo.setReceiverMobile(receiver.getReceiverMobile());
		receiverVo.setReceiverProvince(receiver.getReceiverProvince());
		receiverVo.setReceiverPhone(receiver.getRecelverPhone());
		receiverVo.setReceiverCity(receiver.getReceiverCity());
		receiverVo.setReceiverDistrict(receiver.getReceiverDistrict());
		receiverVo.setReceiverZip(receiver.getReceiverZip());
		return receiverVo;
	}
	/**
	 * 生成支付宝付款二维码
	 * @param orderNo
	 * @param userId
	 * @param path
	 * @return
	 */
	public ServerResponse<Map<String, String>> pay(Long orderNo,Integer userId,String path){
		Map<String,String> resultMap = Maps.newHashMap();
		// 查询出指定用户下的指定订单
		Order order = orderMapper.selectByUserIdAndOrderNo(userId, orderNo);
		System.out.println("打印一下看看");
		System.out.println(order);
		if (order == null) {
			return ServerResponse.createByError("此订单不存在");
		}
		resultMap.put("orderNo", String.valueOf(order.getOrderNo()));

		// (必填) 商户网站订单系统中唯一订单号，64个字符以内，只能包含字母、数字、下划线，
		// 需保证商户系统端不能重复，建议通过数据库sequence生成，
		String outTradeNo = order.getOrderNo().toString();

		// (必填) 订单标题，粗略描述用户的支付目的。如“xxx品牌xxx门店当面付扫码消费”
		String subject = new StringBuilder().append("涛宝商城扫码支付,订单号:").append(outTradeNo).toString();

		// (必填) 订单总金额，单位为元，不能超过1亿元
		// 如果同时传入了【打折金额】,【不可打折金额】,【订单总金额】三者,则必须满足如下条件:【订单总金额】=【打折金额】+【不可打折金额】
		String totalAmount = order.getPayment().toString();

		// (可选) 订单不可打折金额，可以配合商家平台配置折扣活动，如果酒水不参与打折，则将对应金额填写至此字段
		// 如果该值未传入,但传入了【订单总金额】,【打折金额】,则该值默认为【订单总金额】-【打折金额】
		String undiscountableAmount = "0";

		// 卖家支付宝账号ID，用于支持一个签约账号下支持打款到不同的收款账号，(打款到sellerId对应的支付宝账号)
		// 如果该字段为空，则默认为与支付宝签约的商户的PID，也就是appid对应的PID
		String sellerId = "";

		// 订单描述，可以对交易或商品进行一个详细地描述，比如填写"购买商品2件共15.00元"
		String body = new StringBuilder().append("订单").append(outTradeNo).append("购买商品共").append(totalAmount).append("元").toString();

		// 商户操作员编号，添加此参数可以为商户操作员做销售统计
		String operatorId = "test_operator_id";

		// (必填) 商户门店编号，通过门店号和商家后台可以配置精准到门店的折扣信息，详询支付宝技术支持
		String storeId = "test_store_id";

		// 业务扩展参数，目前可添加由支付宝分配的系统商编号(通过setSysServiceProviderId方法)，详情请咨询支付宝技术支持
		ExtendParams extendParams = new ExtendParams();
		extendParams.setSysServiceProviderId("2088100200300400500");

		// 支付超时，定义为120分钟
		String timeoutExpress = "120m";

		// 商品明细列表，需填写购买商品详细信息，
		List<GoodsDetail> goodsDetailList = new ArrayList<GoodsDetail>();

		// 查询出每个订单详情 通过订单详情获取商品信息
		List<OrderItem> orderItems = orderItemMapper.listOrderItemByIdAndUserId(userId, orderNo);

		for (OrderItem orderItem : orderItems) {
			// 获取每个订单详情下的商品信息
			GoodsDetail goods = GoodsDetail.newInstance(new StringBuilder().append("goods_id").append(orderItem.getProductId()).toString(), 
					orderItem.getProductName(), BigDecimalUtil.mul(orderItem.getCurrentUnitPrice().doubleValue(), new Double(100).doubleValue()).longValue(), orderItem.getQuantity());
			goodsDetailList.add(goods);
		}


		// 创建扫码支付请求builder，设置请求参数
		AlipayTradePrecreateRequestBuilder builder = new AlipayTradePrecreateRequestBuilder()
				.setSubject(subject).setTotalAmount(totalAmount).setOutTradeNo(outTradeNo)
				.setUndiscountableAmount(undiscountableAmount).setSellerId(sellerId).setBody(body)
				.setOperatorId(operatorId).setStoreId(storeId).setExtendParams(extendParams)
				.setTimeoutExpress(timeoutExpress)
				.setNotifyUrl(PropertiesUtil.getValue("alipay.callback.url"))//支付宝服务器主动通知商户服务器里指定的页面http路径,根据需要设置
				.setGoodsDetailList(goodsDetailList);

		/** 一定要在创建AlipayTradeService之前调用Configs.init()设置默认参数
		 *  Configs会读取classpath下的zfbinfo.properties文件配置信息，如果找不到该文件则确认该文件是否在classpath目录
		 */
		Configs.init("zfbinfo.properties");

		/** 使用Configs提供的默认参数
		 *  AlipayTradeService可以使用单例或者为静态成员对象，不需要反复new
		 */
		AlipayTradeService tradeService = new AlipayTradeServiceImpl.ClientBuilder().build();

		AlipayF2FPrecreateResult result = tradeService.tradePrecreate(builder);
		switch (result.getTradeStatus()) {
		case SUCCESS:
			log.info("支付宝预下单成功: )");

			AlipayTradePrecreateResponse response = result.getResponse();
			dumpResponse(response);

			File file = new File(path);
			if (!file.exists()) {
				file.setWritable(true);
				file.mkdirs();
			}

			// 需要修改为运行机器上的路径
			String filePath = String.format(path + "/qr-%s.png",response.getOutTradeNo());
			String fileName = String.format("qr-%s.png", response.getOutTradeNo());
			ZxingUtils.getQRCodeImge(response.getQrCode(), 256, filePath);

			File targetFile = new File(path,fileName);

			try {
//				FTPUtil.fileUpload(fileName, new FileInputStream(targetFile));
				AliyunOSSUtil.fileUpload(fileName, new FileInputStream(targetFile));
			} catch (FileNotFoundException e) {
				log.error("二维码上传异常");
			}

			log.info("filePath:" + filePath);
			//                ZxingUtils.getQRCodeImge(response.getQrCode(), 256, filePath);

//			String qrUrl = PropertiesUtil.getValue("FTP_IP")+"/"+fileName;
			String qrUrl = AliyunOSSUtil.fullURL + fileName;
			resultMap.put("qrUrl", qrUrl);
			return ServerResponse.createBySuccess(resultMap);
		case FAILED:
			log.error("支付宝预下单失败!!!");
			return ServerResponse.createByError("支付宝预下单失败!!!");
		case UNKNOWN:
			log.error("系统异常，预下单状态未知!!!");
			return ServerResponse.createByError("系统异常，预下单状态未知!!!");
		default:
			log.error("不支持的交易状态，交易返回异常!!!");
			return ServerResponse.createByError("不支持的交易状态，交易返回异常!!!");
		}
	}


	// 简单打印应答
	private void dumpResponse(AlipayResponse response) {
		if (response != null) {
			log.info(String.format("code:%s, msg:%s", response.getCode(), response.getMsg()));
			if (StringUtils.isNotEmpty(response.getSubCode())) {
				log.info(String.format("subCode:%s, subMsg:%s", response.getSubCode(),
						response.getSubMsg()));
			}
			log.info("body:" + response.getBody());
		}
	}


	public ServerResponse aliCallback(Map<String,String> params) {
		System.out.println("显示"+params);
		Long orderNo = Long.parseLong(params.get("out_trade_no"));
		String tradeNo = params.get("trade_no");
		String tradeStatus = params.get("trade_status");

		Order order = orderMapper.selectByOrderNo(orderNo);
		if (order==null) {
			return ServerResponse.createByError("找不到这个订单,无效的回调");
		}
		if (order.getStatus() >= Const.OrderStatusEnum.PAID.getCode()) {
			return ServerResponse.createBySuccess("支付宝重复调用");
		}
		if (Const.AlipayCallback.TRADE_STATUS_TRADE_SUCCESS.equals(tradeStatus)) {
			// 交易成功 修改订单状态
			order.setPaymentTime(DateTimeUtil.strToDate(params.get("gmt_payment")));
			order.setStatus(Const.OrderStatusEnum.PAID.getCode());
			orderMapper.updateByPrimaryKey(order);
		}
		// 支付成功后新增支付信息记录
		PayInfo payInfo = new PayInfo();
		payInfo.setUserId(order.getUserId());
		payInfo.setOrderNo(order.getOrderNo());
		payInfo.setPayPlatform(Const.PayPlatformEnum.ALIPAY.getCode());
		payInfo.setPlatformNumber(tradeNo);
		payInfo.setPlatformStatus(tradeStatus);
		payInfoMapper.insert(payInfo);
		return ServerResponse.createBySuccess();
	}

	/**
	 * 判断用户订单状态
	 * @param userId
	 * @param orderNo
	 * @return
	 */
	public ServerResponse queryOrderPayStatus(Integer userId,Long orderNo) {
		Order order = orderMapper.selectByUserIdAndOrderNo(userId, orderNo);
		if (order == null) {
			return ServerResponse.createByError("没有该订单!");
		}
		if (order.getStatus() >= Const.OrderStatusEnum.PAID.getCode()) {
			return ServerResponse.createBySuccess();
		}
		return ServerResponse.createByError();
	}

}
